package com.aones.ui.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.base.BaseAdapter
import com.base.utils.LoadImageUtils
import com.somlsis.R

class AddImageAdapter : BaseAdapter<String, AddImageAdapter.ViewHolder> {
    private var listener: OnImageItemClickListener? = null
    private  var widthPixels:Int
    constructor(
        context: Context?,
        onImageItemClickListener: OnImageItemClickListener?
    ) : super(context!!) {
        this.listener = onImageItemClickListener
        widthPixels = context.resources.displayMetrics.widthPixels
    }

    override fun getItemCount(): Int {
        return if (dataList.size == 9) {
            dataList.size
        } else dataList.size + 1
    }

    fun getDataSize(): Int {
        return dataList.size
    }

    override fun onBindView(holder: ViewHolder, position: Int, media: String?) {
        val layoutParams = holder.itemImage.layoutParams
        layoutParams.width =widthPixels * 120 / 720
        layoutParams.height = widthPixels * 120 / 720
        holder.itemImage.layoutParams = layoutParams
        if (position == dataList.size && dataList.size < 9) {
            LoadImageUtils.loadImage(holder.itemImage, R.mipmap.icon_add_pulish_image, 0f)
            holder.itemRemove.visibility = View.GONE
        } else {
            LoadImageUtils.loadImage(holder.itemImage, media, 5f)
            holder.itemRemove.visibility = View.VISIBLE
        }
        holder.itemView.setOnClickListener {
            listener!!.onItemClick(
                dataList.size,
                position
            )
        }
        holder.itemRemove.setOnClickListener {
            listener!!.onItemDeleteClick(position)
            dataList.removeAt(position)
            notifyDataSetChanged()
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val inflate: View =
            LayoutInflater.from(mContext).inflate(R.layout.item_add_image, parent, false)
        return ViewHolder(inflate)
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var itemImage: ImageView = itemView.findViewById(R.id.item_image)
        var itemRemove: ImageView = itemView.findViewById(R.id.item_remove)

    }

    interface OnImageItemClickListener {
        fun onItemClick(size: Int, position: Int)
        fun onItemDeleteClick(position: Int)
    }
}